//import { execSql } from './mysqlDB';
const mysqlDB = require('./mysqlDB')
export const queryModuleList = () => {
  let sql = "select id,name,`schema`,`packages`,assets,release_schema,release_packages,vesion,vesion_remark,state,DATE_FORMAT(release_time, '%Y-%m-%d %H:%i:%s') release_time from low_code_module";
  return mysqlDB.execSql(sql)
}

export const queryModule = (id: number) => {
  let sql = "select id,name,`schema`,`packages`,assets,release_schema,release_packages,vesion,vesion_remark,state,DATE_FORMAT(release_time, '%Y-%m-%d %H:%i:%s') release_time from low_code_module where id=?";
  return mysqlDB.execSql(sql, [id])
}

export const updateModuleName = (id: number, name: string) => {
  let sql = 'update low_code_module set name=?  where id=?';
  return mysqlDB.execSql(sql, [name, id])
}

export const updateModuleSchema = (id: number, values: Array<any>) => {
  let sql = 'update low_code_module set `schema`=?,`packages`=?,state=(case state when 1 then 1 else 3 end) where id=?';
  return mysqlDB.execSql(sql, [...values, id])
}

export const updateModuleRelease = async (id: number, values: Array<any>) => {
  let conn = null;
  let sql1 = 'insert into low_code_module_vesion_his(moduleId,`schema`,`packages`,vesion,remark) select id,`schema`,packages,vesion,vesion_remark from low_code_module where id=?';
  let sql2 = 'update low_code_module set `release_schema`=`schema`,`release_packages`=`packages` ,vesion=?,vesion_remark=?,release_time=NOW(), state=2  where id=?';
  try {
    conn = await mysqlDB.getConnection();
    conn.beginTransaction();
    await conn.execSql(sql1, [id]);
    const data = await conn.execSql(sql2, [...values, id]);
    conn.commit();
    return data;
  } catch (e) {
    conn.rollback();
    throw e;
  } finally {
    if (conn) {
      conn.close()
    }
  }
}

export const addModule = (data: any) => {
  const values = [data.name, data.assets];
  let sql = 'insert into low_code_module(name,assets) values(?)';
  return mysqlDB.execSql(sql, [values])
}

export const deleteModuleById = (id: number) => {
  let sql = 'delete from low_code_module where id=?';
  return mysqlDB.execSql(sql, [id])
}

export const insertModuleVesionHis = (id: number) => {
  let sql = 'insert low_code_module_vesion_his(moduleId,`schema`,`packages`,vesion,remark) select id,release_schema,release_packages,vesion,vesion_remark from low_code_module where id=?';
  return mysqlDB.execSql(sql, [id])
}

